package com.xmqian.app.project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.coszero.utilslibrary.app.AppManager;
import com.coszero.utilslibrary.app.AppUtils;
import com.coszero.utilslibrary.base.BaseTabViewPagerAdapter;
import com.coszero.utilslibrary.utils.LogX;
import com.coszero.utilslibrary.utils.ToastUtils;
import com.xmqian.app.R;
import com.xmqian.app.common.base.MyBaseActivity;
import com.xmqian.app.common.config.user.UserManager;
import com.xmqian.app.common.testdata.TestData;
import com.xmqian.app.project.event.LoginEvent;
import com.xmqian.app.project.main.fragment.MainPage1Fragment;
import com.xmqian.app.project.model.MainBottomMenuModel;
import com.xmqian.app.project.ui.user.activity.LoginActivity;
import com.xmqian.app.project.ui.user.model.LoginModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Desc： 拥有底部切换菜单的主页
 * <p>
 * Author： xmqian
 * Email:xmqian93@163.com
 * Date: 2019/9/19 17:26
 */
public class MainBottomTabActivity extends MyBaseActivity {
    private static final long DELAY_TIME = 1500;//退出间隔时间
    private long lastPressBackKeyTime = 0;
    @BindView(R.id.vp_fragment)
    ViewPager mVpFragment;
    @BindView(R.id.rg_tab)
    RadioGroup mRgTab;
    private List<Fragment> mFragments = new ArrayList<>();
    private List<MainBottomMenuModel> tabMenus = new ArrayList<>();
    private int lastCheckId;

    /**
     * 单例开启页面，如果堆栈中有，则从底部将页面拉上次，上面的页面全部销毁
     */
    public static void startTask(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, MainBottomTabActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView() {
        UserManager.getInstance().saveLoginData(new LoginModel("妖精尾巴毛", "321", TestData.headImage));
        UserManager.getInstance().initLoginData();
        mFragments.add(MainPage1Fragment.newInstance(AppUtils.getString(mActivity, R.string.app_name)));
        mFragments.add(MainPage1Fragment.newInstance("页面一"));
        mFragments.add(MainPage1Fragment.newInstance("页面二"));
        mFragments.add(MainPage1Fragment.newInstance("页面三"));
        mVpFragment.setAdapter(new BaseTabViewPagerAdapter(getSupportFragmentManager(), mFragments));
        mVpFragment.setOffscreenPageLimit(mFragments.size());
        initBottomTabs();
    }

    private void initBottomTabs() {
        tabMenus.add(new MainBottomMenuModel(R.drawable.sl_main_tab1, AppUtils.getString(mActivity, R.string.app_name), R.id.rb_0));
        tabMenus.add(new MainBottomMenuModel(R.drawable.sl_main_tab1, "页面一", R.id.rb_1));
        tabMenus.add(new MainBottomMenuModel(R.drawable.sl_main_tab1, "页面二", R.id.rb_2));
        tabMenus.add(new MainBottomMenuModel(R.drawable.sl_main_tab1, "页面三", R.id.rb_3));
        for (int i = 0; i < tabMenus.size(); i++) {
            RadioButton inflate = (RadioButton) getLayoutInflater().inflate(R.layout.view_radiobutton, null);
            RadioGroup.LayoutParams layoutParams = new RadioGroup.LayoutParams(0, RadioGroup.LayoutParams.WRAP_CONTENT, 1.0f);
            inflate.setLayoutParams(layoutParams);
            inflate.setId(tabMenus.get(i).getViewId());
            AppUtils.setTopIcon(getResources().getDrawable(tabMenus.get(i).getTopDrawable()), inflate);
            inflate.setText(tabMenus.get(i).getTabName());
            mRgTab.addView(inflate);
        }
        mRgTab.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_0:
                    changeFragment(R.id.rb_0, 0);
                    break;
                case R.id.rb_1:
                    changeFragment(R.id.rb_1, 1);
                    break;
                case R.id.rb_2:
                    changeFragment(R.id.rb_2, 2);
                    break;
                case R.id.rb_3:
                    if (!checkLogin()) {
                        mRgTab.check(lastCheckId);
                        return;
                    }
                    changeFragment(R.id.rb_3, 3);
                    break;
            }
        });
        //默认选中第一个页面
        mRgTab.check(R.id.rb_0);
        lastCheckId = R.id.rb_0;
    }

    /**
     * @param lastCheckId 最后选择的id
     * @param i 选择的位置
     */
    private void changeFragment(int lastCheckId, int i) {
        this.lastCheckId = lastCheckId;
        mVpFragment.setCurrentItem(i, false);
    }

    private boolean checkLogin() {
        if (!UserManager.getInstance().isLogin()) {
            ToastUtils.showMsg("请先登录");
            LoginActivity.startActivity(this);
            return false;
        }
        return true;
    }

    @Override
    protected int getContentLayoutRes() {
        return R.layout.activity_main_bottom_tab;
    }

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastPressBackKeyTime < DELAY_TIME) {
            super.onBackPressed();
        } else {
            lastPressBackKeyTime = System.currentTimeMillis();
            ToastUtils.showLongMsg(getResources().getString(R.string.toast_press_again_exit_app));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        if (event.isLogin()) {
            LogX.i("### 登录成功");
            ToastUtils.showMsg("登录成功");
        } else {
            UserManager.getInstance().clearLoginData();
            LogX.i("### 退出登录成功");
            AppManager.getAppManager().finishAllActivity();
        }
    }
}
